package cryptosuite

import (
	"path/filepath"
	"strings"

	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/core/config/lookup"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/core"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/util/pathvar"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/thirdparty/ichain/security/csp"
	"github.com/spf13/cast"
)

// 默认加密配置
const (
	defEnabled       = true
	defHashAlgorithm = csp.SM3
	defLevel         = 256
	defProvider      = csp.GM
)

// ConfigFromBackend 在sdk配置中获取加密配置
func ConfigFromBackend(coreBackend ...core.ConfigBackend) core.CryptoSuiteConfig {
	return &Config{backend: lookup.New(coreBackend...)}
}

type Config struct {
	backend *lookup.ConfigLookup
}

// IsSecurityEnabled 是否开启加密
// @return bool
func (c *Config) IsSecurityEnabled() bool {
	val, ok := c.backend.Lookup("client.BCCSP.security.enabled")
	if !ok {
		return defEnabled
	}
	return cast.ToBool(val)
}

// SecurityAlgorithm 加密的hash函数
// @return string
func (c *Config) SecurityAlgorithm() string {
	val, ok := c.backend.Lookup("client.BCCSP.security.hashAlgorithm")
	if !ok {
		return defHashAlgorithm
	}
	return cast.ToString(val)
}

// SecurityLevel 加密等级
// @return int
func (c *Config) SecurityLevel() int {
	val, ok := c.backend.Lookup("client.BCCSP.security.level")
	if !ok {
		return defLevel
	}
	return cast.ToInt(val)
}

// SecurityProvider sw或者gm
func (c *Config) SecurityProvider() string {
	val, ok := c.backend.Lookup("client.BCCSP.security.default.provider")
	if !ok {
		return strings.ToLower(defProvider)
	}
	return strings.ToLower(cast.ToString(val))
}

// KeyStorePath 密钥存储路径
// @return string
func (c *Config) KeyStorePath() string {
	keystorePath := pathvar.Subst(c.backend.GetString("client.credentialStore.cryptoStore.path"))
	return filepath.Join(keystorePath, "cert")
}
